import { useState } from 'react';
import { fileDelete, fileUpload } from '@/axios/taskBoard/files/files';
import useInputFocusContext from '@/context/InputFocusContext';

const performers: TaskPerformer[] = [
  {
    id: '2',
    name: 'Damir',
    image: 'https://u13-crm-test.gexarus.com/files/upload/files/6606ab7f01e45.jpg'
  },
  {
    id: '4',
    name: 'Josh',
    image: 'https://u13-crm-test.gexarus.com/files/upload/files/6606ab7f01e45.jpg'
  },
  {
    id: '5',
    name: 'Daniel',
    image: 'https://u13-crm-test.gexarus.com/files/upload/files/6606ab7f01e45.jpg'
  },
]

type NewTask = Pick<Task, 'name' | 'tags' | 'end_date' | 'performers' | 'files_gid'> & { files: string | TaskFile, auto: number };

const confgiTask: NewTask = {
  name: '',
  tags: [],
  files: '',
  end_date: '',
  performers: [],
  auto: 0,
  files_gid: '',
};

export const useNewTask = ({ postTask, setOpen, setSendBtn }: { postTask: (task: NewTask) => void, setOpen?: (open: boolean) => void | undefined, setSendBtn(bool: boolean): void }) => {
  const [text, setText] = useState('');
  const [textareaHeight, setTextareaHeight] = useState('30px');
  const [task, setTask] = useState<NewTask>(confgiTask);
  const [files, setFiles] = useState([]);
  const [tags, setTags] = useState<TaskTag[]>([]);

  const handleFileRemove = async (index: number) => {
    const file: TaskFile = files[index];
    await fileDelete({ params: { gid: task.files, file: file.medium } });
    setFiles(prevFiles => prevFiles.filter((_, i) => i !== index));
  };

  const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setText(event.target.value);
    adjustTextareaHeight(event.target);
  };

  const adjustTextareaHeight = (textarea: HTMLTextAreaElement) => {
    textarea.style.height = textareaHeight;
    textarea.style.height = `${textarea.scrollHeight}px`;
  };


  const { removeFocusedInput } = useInputFocusContext();

  const handleClearOnBlur = () => {
    setOpen && setOpen(false);
    setText('');
    setTask(confgiTask);
    setTextareaHeight('30px');
    setFiles([]);
    removeFocusedInput()
  };

  const updateTask = (item: any) => setTask(prev => ({ ...prev, ...item }));

  const sendFiles = async (uploadFiles: File[]) => {
    let formDataFiles = new FormData();
    uploadFiles.forEach((file, i: number) => {
      formDataFiles.append(`files[${i}]`, file);
    });
    formDataFiles.append('gid', `${task.files_gid}`);

    const res = await fileUpload({ params: formDataFiles });
    setTask(prevTask => ({ ...prevTask, files: res.data.id }));
    // @ts-ignore
    setFiles(prevFiles => [...prevFiles, ...res.data.files]);
  };

  const handleSubmit = () => {
    const performersChange = task.performers.map(p => p.id);
    // @ts-ignore
    postTask({ ...task, name: text, performers: performersChange });
    setSendBtn(true)
    removeFocusedInput()
    handleClearOnBlur();
    // setOpen && setOpen(false);
  };

  return {
    text,
    setTask,
    textareaHeight,
    task,
    files,
    performers,
    handleFileRemove,
    handleInputChange,
    handleClearOnBlur,
    updateTask,
    sendFiles,
    handleSubmit,
    tags,
    setTags
  };
};
